<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <template #before>
          <span>共{{ total }}条记录</span>
        </template>
        <template #after>
          <el-button size="small" type="warning" @click="addEmployees">导入</el-button>
          <el-button size="small" type="danger" @click="derive">导出</el-button>
          <el-button
            size="small"
            type="primary"
            @click="dialogVisible = true"
          >新增员工</el-button>
        </template>
      </PageTools>

      <el-card v-loading="loading">
        <el-table
          :data="list"
          border
          style="width: 100%"
        >
          <el-table-column
            type="index"
            label="序号"
            width="60"
          />
          <el-table-column
            prop="username"
            label="姓名"
          />
          <el-table-column
            prop="staffPhoto"
            label="头像"
          >
            <template slot-scope="scope">
              <img v-imgerror="imgUrl" :src="scope.row.staffPhoto" class="img" @click="dialog(scope.row.staffPhoto, '二维码')">
            </template>
          </el-table-column>
          <el-table-column
            prop="workNumber"
            label="工号"
          />
          <el-table-column
            prop="formOfEmployment"
            label="聘用形式"
          >
            <template slot-scope="scope">
              {{ scope.row.formOfEmployment | formOfEmployment }}
            </template>
          </el-table-column>
          <el-table-column
            prop="departmentName"
            label="部门"
          />
          <el-table-column
            prop="timeOfEntry"
            label="入职时间"
          >
            <template slot-scope="scope">
              {{ scope.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column
            prop="enableState"
            label="账户状态"
          >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.enableState"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
              />
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="280"
          >
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push(`/employees/userInfo/${scope.row.id}/${total}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="dialog(scope.row.id,'分配角色')">角色</el-button>
              <el-button type="text" size="small" @click="del(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="prev, pager, next, sizes, total" :total="total" background @size-change="handleSizeChange" @current-change="change" />
        </el-row>
      </el-card>
      <AddEmployee v-if="dialogVisible" :dialog-visible.sync="dialogVisible" :total="total" @upDateRoles="upDateRoles" />
      <el-dialog
        :title="type"
        center
        :visible.sync="dialogVisible1"
        width="40%"
        class="qrcode"
      >
        <canvas v-if="type === '二维码'" ref="canvas" />
        <el-checkbox-group v-else-if="type === '分配角色'" v-model="checkList">
          <el-checkbox v-for="item in checkRows" :key="item.id" :label="item.id">
            {{ item.name }}
          </el-checkbox>
        </el-checkbox-group>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible1 = false">取 消</el-button>
          <el-button type="primary" @click="ensure">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import AddEmployee from './components/addEmployee'
import { uppercaseFirst, formOfEmployment } from '@/filters'
import { getRoles, assignRoles } from '@/api/role'
import { getUser } from '@/api/employees'
import QRCode from 'qrcode'
export default {
  components: {
    AddEmployee
  },
  data() {
    return {
      page: {
        page: 1,
        size: 10
      },
      total: 0,
      list: [],
      loading: false,
      imgUrl: require('@/assets/common/head.jpg'),
      dialogVisible: false,
      type: '',
      dialogVisible1: false,
      checkRows: [],
      checkList: [],
      id: ''
    }
  },
  created() {
    this.getEmployeeList(this.page)
  },
  methods: {
    async getEmployeeList(data) {
      const { total, rows } = await getEmployeeList(data)
      this.list = rows
      this.total = total
      // 每次发请求后都要关闭加载
      this.loading = false
    },
    handleSizeChange(val) {
      this.page.size = val
      this.page.page = 1
      this.getEmployeeList(this.page)
    },
    change(val) {
      this.page.page = val
      this.getEmployeeList(this.page)
    },
    upDateRoles() {
      this.getEmployeeList(this.page)
    },
    del(id) {
      this.$confirm('此操作将永久删除该员工, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delEmployee(id)
        if (this.list.length === 1 && this.page.page !== 1) {
          this.page.page--
        }
        this.change(this.page.page)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    addEmployees() {
      this.$router.push({
        path: '/import',
        query: {
          total: this.total
        }
      })
    },
    derive() {
      const headers = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      import('@/vendor/Export2Excel').then(async excel => {
        const { rows } = await getEmployeeList({ page: this.page.page, size: this.total })
        const list = rows.map(item => {
          return Object.keys(headers).map(key => {
            if (headers[key] === 'formOfEmployment') {
              return formOfEmployment(item[headers[key]])
            } else if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
              return uppercaseFirst(item[headers[key]])
            } else {
              return item[headers[key]]
            }
          })
        })
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        excel.export_json_to_excel({
          header: Object.keys(headers), // 表头 必填 数组类型
          data: list, // 具体数据 必填 数组类型
          filename: 'excel-list', // 非必填
          multiHeader,
          merges,
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },
    async dialog(text, type) {
      this.type = type
      if (type === '二维码') {
        if (text) {
          // dom 操作是异步的
          this.$nextTick(() => {
            QRCode.toCanvas(this.$refs.canvas, text, (err) => {
              if (err) return this.$message.error(err)
            })
          })
        } else {
          this.$message.warning('该用户还未上传头像')
        }
      } else if (type === '分配角色') {
        this.id = text
        const { rows } = await getRoles({ page: 1, pagesize: this.total })
        this.checkRows = rows
        const { roleIds } = await getUser(text)
        this.checkList = roleIds
      }
      this.dialogVisible1 = true
    },
    async ensure() {
      if (this.type === '分配角色') {
        await assignRoles({ id: this.id, roleIds: this.checkList })
      }
      this.dialogVisible1 = false
    }
  }

}
</script>

<style>
.img{
  width: 2.1875rem;
  height: 2.1875rem;
  border-radius: 50%;
}
.qrcode .el-dialog__body{
  text-align: center;
}
</style>
